package org.jeecg.modules.demo.ddyht.controller;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.ddyht.entity.DdygCzrz;
import org.jeecg.modules.demo.ddyht.entity.DdygInventory;
import org.jeecg.modules.demo.ddyht.entity.JxcCostingpici;
import org.jeecg.modules.demo.ddyht.entity.JxcHbzj;
import org.jeecg.modules.demo.ddyht.service.IJxcHbzjService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.demo.jxcx.po.JxcCzrz;
import org.jeecg.modules.demo.jxcx.service.JxcCzrzService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 货币资金
 * @Author: jeecg-boot
 * @Date:   2025-04-13
 * @Version: V1.0
 */
@Api(tags="货币资金")
@RestController
@RequestMapping("/ddyht/jxcHbzj")
@Slf4j
public class JxcHbzjController extends JeecgController<JxcHbzj, IJxcHbzjService> {
	@Autowired
	private IJxcHbzjService jxcHbzjService;
	@Autowired
	private JxcCzrzService jxcCzrzService;
     @Autowired
     private YueController yueController;

	/**
	 * 分页列表查询
	 *
	 * @param jxcHbzj
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "货币资金-分页列表查询")
	@ApiOperation(value="货币资金-分页列表查询", notes="货币资金-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<JxcHbzj>> queryPageList(JxcHbzj jxcHbzj,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
        QueryWrapper<JxcHbzj> queryWrapper = QueryGenerator.initQueryWrapper(jxcHbzj, req.getParameterMap());
		Page<JxcHbzj> page = new Page<JxcHbzj>(pageNo, pageSize);
		IPage<JxcHbzj> pageList = jxcHbzjService.page(page, queryWrapper);
		List<JxcHbzj> company = jxcHbzjService.getBycompany(jxcHbzj.getUsername());
		int size = company.size();
		int page2 = (size + 9) / 10;
		pageList.setTotal(size);
		pageList.setPages(page2);
		pageList.setRecords(company);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param Hbzj
	 * @return
	 */
	@AutoLog(value = "货币资金-添加")
	@ApiOperation(value="货币资金-添加", notes="货币资金-添加")
	@RequiresPermissions("ddyht:jxc_hbzj:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody JxcHbzj Hbzj) {
		String CompanyId  = Hbzj.getUsername();
		String creatTime = Hbzj.getCreateTime();
		String PaymentMethod = Hbzj.getPaymethod();
		BigDecimal allamount = new BigDecimal(Hbzj.getAmount());
		LocalDateTime now = LocalDateTime.now();
		// 定义日期时间格式
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		LocalDateTime dateTime = LocalDateTime.parse(creatTime, formatter);
		DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
		// 格式化当前的日期和时间
		String id = dateTime.format(formatter2);
		DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
		String formattedDateTime = now.format(formatter3);
		if (jxcHbzjService.selectbyPaymentMethod(PaymentMethod,CompanyId) != null){
			JxcHbzj jxcHbzj = jxcHbzjService.selectbyPaymentMethod(PaymentMethod, CompanyId);
			jxcHbzj.setAmount(String.valueOf(new BigDecimal(jxcHbzj.getAmount()).add(allamount)));
			jxcHbzj.setCreateTime(formattedDateTime);
			jxcHbzjService.updateById(jxcHbzj);
		}else {
			JxcHbzj jxcHbzj2 = new JxcHbzj();
			jxcHbzj2.setAmount(String.valueOf(allamount));
			jxcHbzj2.setCompanyId(CompanyId);
			jxcHbzj2.setCreateTime(formattedDateTime);
			jxcHbzj2.setId(id);
			jxcHbzj2.setOther("收入");
			jxcHbzj2.setPaymethod(PaymentMethod);
			jxcHbzjService.save(jxcHbzj2);

		}
		JxcCzrz jxcCzrz = new JxcCzrz();
		jxcCzrz.setId(DdygPiciController.setczrzid(id));
		jxcCzrz.setCompanyId(CompanyId);
		jxcCzrz.setOtherid("货币资金");
		jxcCzrz.setOrstate("期初录入");
		jxcCzrz.setType(PaymentMethod);
		jxcCzrz.setInfor("+" + allamount);
		// 将creatTime从yyyy-MM-dd HH:mm:ss格式转换为yyyy/MM/dd HH:mm:ss格式
		LocalDateTime time = LocalDateTime.parse(creatTime, formatter);
		jxcCzrz.setCreatTime(time.format(formatter3));
		jxcCzrzService.add(jxcCzrz);
//		jxcHbzjService.save(jxcHbzj);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param jxcHbzj
	 * @return
	 */
	@AutoLog(value = "货币资金-编辑")
	@ApiOperation(value="货币资金-编辑", notes="货币资金-编辑")
	@RequiresPermissions("ddyht:jxc_hbzj:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody JxcHbzj jxcHbzj) {
		jxcHbzjService.updateById(jxcHbzj);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "货币资金-通过id删除")
	@ApiOperation(value="货币资金-通过id删除", notes="货币资金-通过id删除")
	@RequiresPermissions("ddyht:jxc_hbzj:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		jxcHbzjService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "货币资金-批量删除")
	@ApiOperation(value="货币资金-批量删除", notes="货币资金-批量删除")
	@RequiresPermissions("ddyht:jxc_hbzj:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.jxcHbzjService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "货币资金-通过id查询")
	@ApiOperation(value="货币资金-通过id查询", notes="货币资金-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<JxcHbzj> queryById(@RequestParam(name="id",required=true) String id) {
		JxcHbzj jxcHbzj = jxcHbzjService.getById(id);
		if(jxcHbzj==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(jxcHbzj);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param jxcCzrz
    */
    @RequiresPermissions("ddyht:jxc_hbzj:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, DdygCzrz jxcCzrz) {
        return exportXls3(request, jxcCzrz, DdygCzrz.class, "货币资金");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("ddyht:jxc_hbzj:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, JxcHbzj.class);
    }
	 public ModelAndView exportXls3(HttpServletRequest request, DdygCzrz object, Class<DdygCzrz> clazz, String title) {
		 // Step.1 组装查询条件
		 QueryWrapper<DdygCzrz> queryWrapper = QueryGenerator.initQueryWrapper(object, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 log.info("selections {}", selections);
		 if (oConvertUtils.isNotEmpty(selections)) {
			 log.info("selections {}", selections);
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 log.info("selectionList {}", selectionList);
			 queryWrapper.in("id",selectionList);
		 }
		 List<DdygCzrz> exportList = new ArrayList<DdygCzrz>();
		 // Step.2 获取导出数据
		 if (oConvertUtils.isNotEmpty(selections)){
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 List<DdygCzrz> jxcCzrzs = new ArrayList<DdygCzrz>();
			 for (int i = 0; i < selectionList.size(); i++) {
				 String id = selectionList.get(i);
				 JxcHbzj byId = jxcHbzjService.getById(id);
				 String paymethod = byId.getPaymethod();
				 List<DdygCzrz> Bypaymethod = jxcHbzjService.getBypaymethod(object.getUsername(), "货币资金", paymethod);
				 for (int i1 = 0; i1 < Bypaymethod.size(); i1++) {
					 Bypaymethod.get(i1).setCreatTime(Bypaymethod.get(i1).getCreatTime().substring(0, 10));
					 exportList.add(Bypaymethod.get(i1));
				 }
			 }
		 }else {
			 List<DdygCzrz> bycompanySale = jxcHbzjService.getBycompanyOr(object.getUsername(), "货币资金");
			 for (int i = 0; i < bycompanySale.size(); i++){
				 bycompanySale.get(i).setCreatTime(bycompanySale.get(i).getCreatTime().substring(0, 10));
			 }
			 exportList = bycompanySale;
		 }
		 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
		 exportList.sort((o1, o2) -> {
			 LocalDate date1 = LocalDate.parse(o1.getCreatTime(), formatter);
			 LocalDate date2 = LocalDate.parse(o2.getCreatTime(), formatter);
			 return date2.compareTo(date1); // 最新在前
		 });
		 log.info("exportList {}", exportList);

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.FILE_NAME, title);
		 mv.addObject(NormalExcelConstants.CLASS, clazz);
		 ExportParams exportParams=new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title);
		 exportParams.setImageBasePath("C:/upload/sc");
		 mv.addObject(NormalExcelConstants.PARAMS,exportParams);
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
	 }
}
